<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-container">
      <div class="modal-header">
        <h3>编辑Excel模板</h3>
        <button class="close-button" @click="handleClose">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <div class="modal-body">
        <div v-if="loading" class="loading-container">
          <i class="fas fa-spinner fa-spin"></i>
          <p>{{ loadingMessage }}</p>
        </div>
        
        <div v-else ref="hotTableContainer" class="hot-table-container">
          <hot-table
            ref="hotTable"
            :settings="hotSettings"
            :data="tableData"
            licenseKey="non-commercial-and-evaluation"
          />
        </div>
      </div>

      <div class="modal-footer">
        <button 
          class="btn-secondary" 
          @click="handleClose"
        >
          取消
        </button>
        <button 
          class="btn-primary" 
          @click="handleSave"
          :disabled="loading"
        >
          保存
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { HotTable } from '@handsontable/vue3'
import 'handsontable/dist/handsontable.full.css'
import * as XLSX from 'xlsx'
import { API_URL } from '../config/apiConfig'
import { checkFileExists, saveFile, readExcelFile } from '../scripts/electronIPC'
import { addAuthHeader } from '../scripts/api/apiUtils'
const props = defineProps<{
  show: boolean
  templateId: string
  fileName: string
}>()

const emit = defineEmits<{
  'update:show': [value: boolean]
  'save-success': []
  'close': []
}>()

const hotTable = ref()
const tableData = ref<any[][]>([])
const loading = ref(false)
const loadingMessage = ref('')

// Handsontable 配置
const hotSettings = {
  rowHeaders: true,
  colHeaders: true,
  licenseKey: 'non-commercial-and-evaluation',
  height: 'auto',
  width: 'auto',
  stretchH: 'all'
}

// 解析Excel文件
const parseExcelFile = async (fileBuffer: Uint8Array) => {
  try {
    const workbook = XLSX.read(fileBuffer, { type: 'buffer' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    return XLSX.utils.sheet_to_json(worksheet, { header: 1 })
  } catch (error) {
    console.error('解析Excel文件失败:', error)
    throw error
  }
}

// 下载并保存文件
const downloadAndSaveFile = async (templateId: string, fileName: string) => {
  try {
    loadingMessage.value = '正在下载文件...'
    const response = await fetch(`${API_URL}/demo/rule-template/${templateId}/download`, addAuthHeader({
      method: 'GET',
      credentials: 'include'
    }))
    
    if (!response.ok) {
      throw new Error(`下载失败: ${response.status}`)
    }
    
    // 对于文件下载，我们不需要处理JSON，直接获取blob即可
    const blob = await response.blob()
    const buffer = await blob.arrayBuffer()
    
    await saveFile(fileName, new Uint8Array(buffer))
    
    return true
  } catch (error) {
    console.error('下载并保存文件失败:', error)
    throw error
  }
}

// 加载Excel数据
const loadExcelData = async () => {
  try {
    loading.value = true
    loadingMessage.value = '正在检查文件...'
    
    const fileExists = await checkFileExists(props.fileName)
    
    if (!fileExists) {
      loadingMessage.value = '正在下载文件...'
      await downloadAndSaveFile(props.templateId, props.fileName)
    }
    
    loadingMessage.value = '正在加载数据...'
    const fileBuffer = await readExcelFile(props.fileName)
    const data = await parseExcelFile(fileBuffer)
    // 添加类型断言，确保数据是二维数组
    tableData.value = data as any[][]
  } catch (error) {
    console.error('加载Excel数据失败:', error)
    alert('加载Excel数据失败: ' + (error instanceof Error ? error.message : String(error)))
  } finally {
    loading.value = false
  }
}

// 保存文件到服务器和本地
const saveToServer = async () => {
  try {
    loading.value = true
    loadingMessage.value = '正在保存...'
    
    // 获取当前表格数据
    const currentData = hotTable.value.hotInstance.getData()
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.aoa_to_sheet(currentData)
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
    
    // 转换为二进制数据
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    
    // 保存到本地文件系统
    loadingMessage.value = '正在保存到本地...'
    // 使用Uint8Array代替Buffer，因为在浏览器环境中Buffer可能不可用
    await saveFile(props.fileName, new Uint8Array(excelBuffer))
    
    // 创建FormData
    loadingMessage.value = '正在上传到服务器...'
    const formData = new FormData()
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    formData.append('file', blob, props.fileName)
    
    // 发送到服务器
    const response = await fetch(`${API_URL}/demo/rule/upload`, addAuthHeader({
      method: 'POST',
      credentials: 'include',
      body: formData
    }))
    // 对于文件上传，我们不需要处理JSON响应中的大整数问题
    
    if (!response.ok) {
      throw new Error(`上传失败: ${response.status}`)
    }
    
    emit('save-success')
    handleClose()
  } catch (error) {
    console.error('保存文件失败:', error)
    alert('保存文件失败: ' + (error instanceof Error ? error.message : String(error)))
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  // 重置状态
  tableData.value = []
  loading.value = false
  loadingMessage.value = ''
  
  // 通知父组件关闭
  emit('update:show', false)
  emit('close')
}

const handleSave = () => {
  saveToServer()
}

watch(() => props.show, (newValue) => {
  if (newValue) {
    loadExcelData()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 1200px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 1rem;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  flex: 1;
  padding: 1rem;
  overflow: auto;
  min-height: 400px;
  position: relative;
}

.modal-footer {
  padding: 1rem;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.loading-container i {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.hot-table-container {
  height: 100%;
  width: 100%;
}

.close-button {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0.5rem;
  color: #666;
}

.close-button:hover {
  color: #333;
}
</style>